import React, { useEffect, useState } from 'react';
import { Spin } from 'antd';
import { command } from '@/ts/base';
import orgCtrl from '@/ts/controller';
import { IFile, IWorkTask, IWork } from '@/ts/core';
import { useFlagCmdEmitter } from '@/hooks/useCtrlUpdate';
import { loadFileMenus } from '@/executor/fileOperate';
import { cleanMenus } from '@/utils/tools';
import FullScreenModal from '@/components/Common/fullScreen';
import DirectoryViewer from '@/components/Directory/views';
import OrgIcons from '@/components/Common/GlobalComps/orgIcons';
import AppLayout from '@/components/MainLayout/appLayout';
import useTimeoutHanlder from '@/hooks/useTimeoutHanlder';
import SelectWork from '../../../../Work/select';
interface IProps {
  item: IFile;
  openType: number;
}
// 工作台
const HomeWork: React.FC<IProps> = ({ item, openType }) => {
  if (!item || openType !== 2) {
    return <></>;
  }
  const [loaded, setLoaded] = useState(true);
  const [selectOpen, setSelectOpen] = useState(false);
  const [currentTag, setCurrentTag] = useState('待办');
  const [content, setContent] = useState<IFile[]>([]);
  const [focusFile, setFocusFile] = useState<IFile>();
  const [submitHanlder, clearHanlder] = useTimeoutHanlder();
  const [, key] = useFlagCmdEmitter('_commons', () => {
    if (currentTag === '常用') {
      loadContent('常用');
    }
  });
  useEffect(() => {
    const id = orgCtrl.work.notity.subscribe((..._args) => {
      loadContent('待办');
    });
    return () => {
      orgCtrl.work.notity.unsubscribe(id);
    };
  }, []);

  useEffect(() => {
    const id = command.subscribe((type, cmd, ...args: any[]) => {
      if (type != 'data') return;
      switch (cmd) {
        case 'loadMoreData':
          loadTasks(args[0][1], args[0][0]);
          break;
      }
    });
    return () => {
      command.unsubscribe(id);
    };
  }, []);

  useEffect(() => {
    command.emitter('preview', 'work', focusFile);
  }, [focusFile]);

  const contextMenu = (file?: IFile) => {
    return {
      items: cleanMenus(loadFileMenus(file)) || [],
      onClick: ({ key }: { key: string }) => {
        command.emitter('executor', key, file);
      },
    };
  };

  const focusHanlder = (file: IFile | undefined) => {
    if (file && file.key !== focusFile?.key) {
      setFocusFile(file);
    }
  };

  const clickHanlder = (file: IFile | undefined, dblclick: boolean) => {
    if (dblclick && currentTag !== '草稿') {
      clearHanlder();
      if (file) {
        command.emitter('executor', 'open', file);
      }
    } else {
      submitHanlder(() => focusHanlder(file), 200);
    }
  };
  const findTodo = (todos: any, groupName: any) => {
    return todos.filter((item: any) => {
      return item.groupTags.includes(groupName);
    });
  };
  const getBadgeCount = (tag: string) => {
    if (tag === '待办') {
      return findTodo(orgCtrl.work.todos, item.name).length;
    }
    return 0;
  };

  const loadContent = (tag: string) => {
    loadTasks(tag);
  };
  const loadTasks = (tag: string, args?: IWorkTask[]) => {
    setLoaded(false);
    const oldContent: IWorkTask[] = args || [];
    const newTasks = [...oldContent, ...findTodo(orgCtrl.work.todos, item.name)].sort(
      (a, b) => {
        return (
          new Date(b?.taskdata.updateTime).getTime() -
          new Date(a?.taskdata.updateTime).getTime()
        );
      },
    );
    setCurrentTag(tag);
    setContent([...newTasks]);
    if (
      tag === '待办' &&
      newTasks.length > 0 &&
      (currentTag != tag || focusFile == undefined)
    ) {
      setFocusFile(newTasks[0]);
    }
    setLoaded(true);
  };
  return (
    <AppLayout previewFlag={'work'}>
      <Spin spinning={!loaded} tip={'加载中...'}>
        <div key={key} style={{ marginLeft: 10, padding: 2, fontSize: 16 }}>
          <OrgIcons type="navbar/work" />
          <span style={{ paddingLeft: 10 }}>办事</span>
        </div>
        <DirectoryViewer
          isMenu
          extraTags={false}
          currentTag={currentTag}
          height={'calc(100% - 110px)'}
          selectFiles={[]}
          focusFile={focusFile}
          content={content}
          badgeCount={getBadgeCount}
          tagChanged={(t) => loadContent(t)}
          initTags={['待办']}
          fileOpen={(entity, dblclick) => clickHanlder(entity as IWorkTask, dblclick)}
          contextMenu={(entity) => contextMenu(entity as IWorkTask)}
        />
        {selectOpen && (
          <FullScreenModal
            open
            title={'选择办事'}
            onCancel={() => {
              setSelectOpen(false);
            }}
            destroyOnClose
            width={1000}
            bodyHeight={'75vh'}>
            <SelectWork
              onSelected={(work: IWork) => {
                setSelectOpen(false);
                setTimeout(() => {
                  setFocusFile(work);
                }, 500);
              }}
            />
          </FullScreenModal>
        )}
      </Spin>
    </AppLayout>
  );
};

export default HomeWork;
